package com.yyn.client2.dao;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

//客户端
@Service
public class ClientDao {
    SocketChannel socketChannel ;
    public void client(String name,String toName) throws IOException {
        socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9001));
        Selector selector = Selector.open();
        System.out.println("客户A地址：" + socketChannel.getLocalAddress());
        socketChannel.configureBlocking(false);
//        监听读事件
//        socketChannel.register(selector,SelectionKey.OP_CONNECT);
        socketChannel.register(selector, SelectionKey.OP_READ);
        while (true) {
            new WriterThread(name, socketChannel,toName).start();
            int select = selector.select();
            if (select == 0) {
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();//获取到所有的通道
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
//                if(key.isReadable()){
//                    SocketChannel channel = (SocketChannel) key.channel();
//                    boolean connect = channel.connect(new InetSocketAddress("127.0.0.1", 9003));
//                    System.out.println(connect);
//                }
                if (key.isReadable()) {
                    handleRead(key);
                    iterator.remove();
                }
            }

        }

    }

    private void handleRead(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int len = 0;
        String message = "";
        while ((len = channel.read(buffer)) > 0) {
            buffer.flip();
            message += new String(buffer.array(), 0, len);
        }
        System.out.println("接到服务端的消息：" + message);
//        让该通道 继续监听 服务端发送的消息    写的操作让另一条线程来执行
        channel.register(key.selector(), SelectionKey.OP_READ);
    }

    public void privateChat(String name) {
        System.out.println("与谁聊天请输入：");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.next();
        try {
            socketChannel.write(ByteBuffer.wrap((name + "连接:" + s).getBytes(StandardCharsets.UTF_8)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}